// #ifdef MP-WEIXIN
const fsm = uni.getFileSystemManager();
// #endif
// #ifdef MP-ALIPAY
const fsm = my.getFileSystemManager();
// #endif
const FILE_BASE_NAME = 'tmp_base64src'; //自定义文件名

function GenNonDuplicateID(randomLength) {
	return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
}

function base64src(base64data, cb) {
	const str = '_' + GenNonDuplicateID(6);
	const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
	if (!format) {
		return new Error('ERROR_BASE64SRC_PARSE');
	}
	// #ifdef MP-WEIXIN
	let filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}${str}.${format}`;
	// #endif
	// #ifdef MP-ALIPAY
	let filePath = `${my.env.USER_DATA_PATH}/${FILE_BASE_NAME}${str}.${format}`;
	// #endif
	const buffer = uni.base64ToArrayBuffer(bodyData);
	// filePath = filePath.replace('https', 'http')
	// console.log(filePath, 'filePath')
	fsm.writeFile({
		filePath,
		data: buffer,
		encoding: 'binary',

		success() {
			uni.hideLoading()
			cb(filePath);
		},

		fail() {
			uni.hideLoading()
			cb(new Error('base64路径生成错误'))
			return new Error('ERROR_BASE64SRC_WRITE');
		}

	});
}


export {
	base64src
};
